import { Component, OnInit, ViewChild, ViewChildren, QueryList, ElementRef, Injector } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AddBase } from 'app/modules/base/add-base';
import { markAllAsTouched } from 'app/modules/base/helper';
import { SoftwareService, PackageInfo } from '../../services/software.service';
import { ApiDataTableComponent } from 'app/modules/share/components/api-data-table/api-data-table.component';
import { MySelection } from 'app/modules/base/selection';
import { map, tap } from 'rxjs/operators';

@Component({
	selector: 'm-add',
	templateUrl: './add.component.html',
	styleUrls: ['./add.component.scss'],
})
export class AddComponent extends AddBase implements OnInit {
	constructor(injector: Injector, private softManager: SoftwareService) {
		super(injector);
	}
	packageDataSource = this.softManager.packages();
	current = '';
	submitted = false;
	selection = new MySelection<PackageInfo>('id');
	packages$ = this.selection.change.pipe(
		map(() => this.selection.selected),
		tap(packages => {
			debugger
			if (!packages.length) {
				return;
			}
			if (!packages.find(pkg => pkg.id.toString() == this.current)) {
				this.current = packages[0].id.toString();
			}
		}),
	);
	@ViewChildren(NgForm) ngForms: QueryList<NgForm>;
	@ViewChildren('formRef') formRefs: QueryList<ElementRef<HTMLFormElement>>;

	category$ = this.softManager.category();
	ngOnInit() {}

	async submit() {
		this.submitted = true;
		if (!this.ngForms.length) {
			this.toastr.info('请选择软件包，并标记信息后提交');
			return;
		}
		for (const ngForm of this.ngForms.toArray()) {
			ngForm.onSubmit(null);
			if (!ngForm.valid) {
				this.toastr.info('请标记必填项信息');
			}
			markAllAsTouched(ngForm.form);
			if (ngForm.invalid) {
				this.current = ngForm.value['ids'];
				return;
			}
		}
		const formData = new FormData();
		for (const formRef of this.formRefs.toArray()) {
			new FormData(formRef.nativeElement).forEach((v, k) => {
				if (k === 'icons' && v instanceof File) {
					if (!v.name) {
						formData.append('icon_file_index', '-1');
						return;
					}
					formData.append('icon_file_index', formData.getAll('icons').length.toString());
				}
				formData.append(k, v);
			});
		}
	   
		await this.softManager.create(formData);
		this.back();
	}
}
